﻿using Common.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xmart.Action;

namespace Xmart.UI
{
    public class UIProvider : IUIProvider
    {
        ILog log = LogManager.GetCurrentClassLogger();

        public virtual Action.ActionResult Execute(string name, params object[] args)
        {
            ActionResult ar = new ActionResult();
            log.DebugFormat("Execute:{0},Args{1}", name, args);
            try
            {
                var mi = FindMethod(name, args);

                log.DebugFormat("FindMethod:{0}", mi);

                ar = mi.Invoke(this, args) as ActionResult;
                ar.Success = true;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error:{0}", ex, name);
                ar.Append("{0}:{1}", name, ex.Message);
                ar.State = -1;
                ar.Success = false;
            }

            return ar;
        }

        private System.Reflection.MethodInfo FindMethod(string key, object[] args)
        {
            Type[] typeArgs = Type.EmptyTypes;

            if (args != null && args.Length > 0)
            {
                typeArgs = (from p in args where p != null select p.GetType()).ToArray();
            }

            return Spring.Util.ReflectionUtils.GetMethod(GetType(), key, typeArgs);
        }

    }
}
